package com.mx.web.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter;

import com.mx.web.service.UserService;

/**
 * Security配置
 * @author maxu at 2015年10月23日
 */

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	private static final Logger logger = LoggerFactory.getLogger(SecurityConfig.class);

	protected void configure(HttpSecurity http) throws Exception {
		http
			.csrf().disable()
			.headers()
				.addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN))
				.and()
			.formLogin()
				.defaultSuccessUrl("/index.html")		//登录成功跳转的页面
				.loginPage("/signin.jsp")				//登录页面
				.failureUrl("/signin.jsp?error")		//登录错误页面
				.permitAll()
				.and()
			.logout()
				.logoutSuccessUrl("/signin.jsp?logout")	//注销成功的页面
				.logoutUrl("/logout.html")				//注销路径，并没有存在
				.permitAll()
				.and()
			.authorizeRequests()
				.antMatchers("/back/**")				//对后台所有页面进行验证
				.authenticated();
	}

	//自己实现DetailsService，完成自定义认证
	@Override
	protected void configure(AuthenticationManagerBuilder auth)
			throws Exception {
		logger.info("进入自定义UserDetailsService-->config");
		auth.userDetailsService(userService());
	}
	
	@Bean
	protected UserService userService()
			throws Exception {
		logger.info("进入自定义UserDetailsService-->userService");
		return new UserService();
	}
}
